# -*- coding: utf-8 -*-
# @Time : 2023/7/30 18:34
# @Author : zxp
from rest_framework import serializers

from article.models import Article
from comment.models import Comment
from user_info.serializers import UserDetailSerializer


class CommentChildrenSerializer(serializers.ModelSerializer):
    """子评论的序列化器"""

    url = serializers.HyperlinkedIdentityField(view_name='comment-detail')
    author = UserDetailSerializer(read_only=True)

    class Meta:
        model = Comment
        exclude = ['parent', 'article']


class CommentSerializer(serializers.ModelSerializer):
    """评论序列化器"""

    url = serializers.HyperlinkedIdentityField(view_name='comment-detail')
    author = UserDetailSerializer(read_only=True)

    # HyperlinkedRelatedField用法同HyperlinkedIdentityField
    article = serializers.HyperlinkedRelatedField(view_name='article-detail', read_only=True)
    article_id = serializers.IntegerField(write_only=True, allow_null=False, required=True)

    parent = CommentChildrenSerializer(read_only=True)
    parent_id = serializers.IntegerField(write_only=True, allow_null=True, required=False)

    # article_id是否存在
    def validate_article_id(self, value):
        if not Article.objects.filter(id=value).exists() and value is not None:
            raise serializers.ValidationError("Article with id {} not exists.".format(value))
        return value  # 放行

    # parent_id是否存在
    def validate_parent_id(self, value):
        if not Comment.objects.filter(id=value).exists() and value is not None:
            raise serializers.ValidationError("Comment with id {} not exists.".format(value))
        return value  # 放行

    def update(self, instance, validated_data):
        validated_data.pop('parent_id', None)  # 评论更新时，不可更新其父评论主键，故将传进来的去掉
        return super().update(instance, validated_data)

    class Meta:
        model = Comment
        fields = '__all__'
        extra_kwargs = {'create_datetime': {'read_only': True}}

